import os
import sys

# 配置输出文件
OUTPUT_FILE = 'python_code.md'

# 获取当前文件名，用于排除
current_file = os.path.basename(__file__)

# 函数：处理单个 Python 文件
def process_python_file(file_path, md_file):
    try:
        with open(file_path, 'r', encoding='utf-8') as py_file:
            content = py_file.read()
            md_file.write(f'### 文件路径: `{file_path}`\n\n')
            md_file.write('```python\n')
            md_file.write(content)
            if not content.endswith('\n'):
                md_file.write('\n')  # 确保代码块以换行符结尾
            md_file.write('```\n\n')
    except Exception as e:
        md_file.write(f'### 文件路径: `{file_path}`\n\n')
        md_file.write(f'```python\n# 读取文件错误: {str(e)}\n```\n\n')

# 打开输出文件并写入内容
with open(OUTPUT_FILE, 'w', encoding='utf-8') as md_file:
    # 遍历当前目录
    for root, _, files in os.walk('.'):  # 使用 _ 忽略子目录列表
        for file in files:
            if file.endswith('.py') and file != current_file:
                file_path = os.path.join(root, file)
                process_python_file(file_path, md_file)

print(f"生成完成！输出文件: {OUTPUT_FILE}")